package com.seselin.citypicker.view;

import android.app.Dialog;
import android.content.Context;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.google.gson.Gson;
import com.seselin.citypicker.R;
import com.seselin.citypicker.bean.CountryBean;
import com.seselin.wheel.OnWheelChangedListener;
import com.seselin.wheel.WheelView;
import com.seselin.wheel.adapters.ArrayWheelAdapter;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 省市二级选择
 */
public class CityPicker extends Dialog implements OnWheelChangedListener {

    private Context context;

    private WheelView mViewProvince;

    private WheelView mViewCity;

    private WheelView mViewDistrict;

    /**
     * 所有省
     */
    private String[] mProvinceData;

    /**
     * key - 省 value - 市
     */
    private Map<String, String[]> mCityDataMap = new HashMap<>();

    /**
     * key - 市 values - 区
     */
    private Map<String, String[]> mDistrictDataMap = new HashMap<>();

    /**
     * 当前省的名称
     */
    private String mCurrentProvinceName;

    /**
     * 当前市的名称
     */
    private String mCurrentCityName;

    /**
     * 当前区的名称
     */
    private String mCurrentDistrictName = "";

    private OnPickerListener listener;

    public interface OnPickerListener {
        void onConfirmClick(String... citySelected);
    }

    public void setOnPickerListener(OnPickerListener listener) {
        this.listener = listener;
    }

    public CityPicker(final Context context) {
        super(context, R.style.MenuDialogStyle);
        this.context = context;
        LayoutInflater layoutInflater = LayoutInflater.from(context);
        View view = layoutInflater.inflate(R.layout.pop_city_picker, null);

        mViewProvince = (WheelView) view.findViewById(R.id.id_province);
        mViewCity = (WheelView) view.findViewById(R.id.id_city);
        mViewDistrict = (WheelView) view.findViewById(R.id.id_district);
        TextView mTvOK = (TextView) view.findViewById(R.id.tv_confirm);
        TextView mTvCancel = (TextView) view.findViewById(R.id.tv_cancel);

        setContentView(view);
        Window window = this.getWindow();
        if (window == null)
            return;
        window.getDecorView().setPadding(0, 0, 0, 0);
        window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
        WindowManager.LayoutParams layoutParams = getWindow().getAttributes();
        layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
        window.setAttributes(layoutParams);
        window.setGravity(Gravity.BOTTOM);
        window.setWindowAnimations(R.style.MenuAnim);

        //初始化城市数据
        initData();

        setUpData();
        mViewProvince.addChangingListener(this);
        mViewCity.addChangingListener(this);
        mViewDistrict.addChangingListener(this);
        mTvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                hide();
            }
        });
        mTvOK.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (listener != null && country != null) {
                    CountryBean.Province province = country.getProvinces().get(mViewProvince.getCurrentItem());
                    CountryBean.Province.City city = province.getCityList().get(mViewCity.getCurrentItem());
                    listener.onConfirmClick(mCurrentProvinceName, mCurrentCityName
                            , province.getId(), city.getId());
                }
                hide();
            }
        });


    }


    private void setUpData() {
        mViewProvince.setViewAdapter(new ArrayWheelAdapter<>(context, mProvinceData));
        // 设置可见条目数量
        mViewProvince.setVisibleItems(5);
        mViewCity.setVisibleItems(5);
        mViewDistrict.setVisibleItems(5);
        mViewProvince.setCyclic(true);
        mViewCity.setCyclic(false);
        mViewDistrict.setCyclic(false);
        mViewProvince.setCurrentItem(0);
        updateCities();
        updateAreas();
    }

    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateAreas() {
        int pCurrent = mViewCity.getCurrentItem();
        mCurrentCityName = mCityDataMap.get(mCurrentProvinceName)[pCurrent];
        String[] areas = mDistrictDataMap.get(mCurrentCityName);

        if (areas == null) {
            areas = new String[]{""};
        }
        mViewDistrict.setViewAdapter(new ArrayWheelAdapter<>(context, areas));
        mViewDistrict.setCurrentItem(0);

        //获取第一个区名称
        mCurrentDistrictName = mDistrictDataMap.get(mCurrentCityName)[0];
    }

    /**
     * 根据当前的省，更新市WheelView的信息
     */
    private void updateCities() {
        int pCurrent = mViewProvince.getCurrentItem();
        mCurrentProvinceName = mProvinceData[pCurrent];
        String[] cities = mCityDataMap.get(mCurrentProvinceName);
        if (cities == null) {
            cities = new String[]{""};
        }
        mViewCity.setViewAdapter(new ArrayWheelAdapter<>(context, cities));
        mViewCity.setCurrentItem(0);
        updateAreas();
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {
        try {
            if (wheel == mViewProvince) {
                updateCities();
            } else if (wheel == mViewCity) {
                updateAreas();
            } else if (wheel == mViewDistrict) {
                mCurrentDistrictName = mDistrictDataMap.get(mCurrentCityName)[newValue];
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private CountryBean country;

    private void initData() {
        country = getCountryBean();
        if (country == null)
            return;
        List<CountryBean.Province> provinces = country.getProvinces();
        mProvinceData = new String[provinces.size()];
        for (int i = 0; i < provinces.size(); i++) {
            mProvinceData[i] = provinces.get(i).getName();
            List<CountryBean.Province.City> cities = provinces.get(i).getCityList();
            String[] mCitiesData = new String[cities.size()];
            for (int j = 0; j < cities.size(); j++) {
                mCitiesData[j] = cities.get(j).getName();
                List<CountryBean.Province.City.Area> areas = cities.get(j).getAreaList();

                String[] mAreasData;
                if (areas.size() > 0)
                    mAreasData = new String[areas.size()];// 当前市的所有区
                else {
                    mAreasData = new String[1];
                    mAreasData[0] = mCitiesData[j];
                }
                for (int k = 0; k < areas.size(); k++) {
                    String area = areas.get(k).getName();// 区域的名称
                    mAreasData[k] = area;
                }

                mDistrictDataMap.put(mCitiesData[j], mAreasData);
                cities.get(j).setAreaList(areas);
            }

            mCityDataMap.put(mProvinceData[i], mCitiesData);
            provinces.get(i).setCityList(cities);
        }
    }

    /**
     * 从assert文件夹中读取省市区的json文件，然后转化为json对象
     */
    private CountryBean getCountryBean() {
        try {
            StringBuilder sb = new StringBuilder();
            InputStream is = context.getAssets().open("city.json");
            int len;
            byte[] buf = new byte[1024 * 50];
            while ((len = is.read(buf)) != -1) {
                sb.append(new String(buf, 0, len, "utf-8"));
            }
            is.close();
            Gson gson = new Gson();
            return gson.fromJson(sb.toString(), CountryBean.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
